Skip to main content

K-means, step by step

PLS 206: Applied Multivariate Modeling

K-means in four moves: drop k centres at random, assign every point to its nearest centre, move every centre to the mean of its points, repeat until nothing changes. Everything below runs in your browser.

Step through k-means

Grey dots are the data. Big dots with a white cross are the centres. Each press of Step does one of two things, in turn:

  1. Assign: every point joins its nearest centre (the coloured lines).
  2. Move: every centre jumps to the mean of its points (the dotted trail).

It stops when an assign step changes nothing.

Data

Number of clusters, k

Total within SS after each step of this start.

Final total within SS of each start. nstart = 25 runs 25 starts and keeps the lowest.

Choosing k

Same data, same scaling as above. Both curves update when you change the data or the scaling.

Elbow

Total within SS always drops as k grows. Look for the bend, where one more cluster stops buying much.

Average silhouette

How much closer each point is to its own cluster than to the next one, averaged. Near 1: tight, separate clusters. Near 0: points sit between clusters. Pick the peak.

Try this

  1. Three blobs, k = 3. Press Step slowly. Watch total within SS: it only ever goes down.
  2. Three blobs, k = 4 or 5. Press New random start a few times and run each one. Do the starts all land on the same answer? The bars show why R keeps the best of many starts.
  3. Height vs seed mass, k = 2. Run it, then tick Scale variables. Which split matches the two groups you can see?
  4. No real clusters, k = 3. k-means still hands you three clusters. Now look at Choosing k: no clear elbow, and a low silhouette.
  5. Two moons or Ring, k = 2. k-means cuts with straight lines. It finds round blobs, not shapes.

The same thing in R

X  <- scale(dat[, c("height", "seed_mass")])   # z-scores: every variable counts equally
km <- kmeans(X, centers = 3, nstart = 25)      # 25 random starts, keep the lowest within SS
km$tot.withinss                                # total within SS
km$cluster                                     # which cluster each row joined

This page uses the simplest version of k-means (assign, move, repeat). R’s default algorithm takes smarter steps but chases the same goal: the lowest total within SS.